package net.oschina.j2cache.redis;

import net.oschina.j2cache.Cache;
import net.oschina.j2cache.CacheException;
import net.oschina.j2cache.CacheExpiredListener;
import net.oschina.j2cache.CacheProvider;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.exceptions.JedisConnectionException;

/**
 * Redis 缓存实现
 * @author Winter Lau
 */
public class RedisCacheProvider implements CacheProvider {


	@Override
	public Cache buildCache(String regionName, boolean autoCreate, CacheExpiredListener listener) throws CacheException {
        boolean borrowOrOprSuccess = true;
        BinaryJedis jedis = null;
        try {
            jedis = RedisPool.me().getResource();
            RedisCache cache = new RedisCache(regionName, jedis);
			return cache;
		} catch (JedisConnectionException e) {
            borrowOrOprSuccess = false;
            if (jedis != null)
                RedisPool.me().returnBrokenResource(jedis);
        } finally {
            if (borrowOrOprSuccess)
                RedisPool.me().returnResource(jedis);
        }
        return null;
    }

	@Override
	public void start() throws CacheException {
	}

	@Override
	public void stop() {
		RedisPool.me().destroy();
	}

}
